#include "synchrotimerclient.h"
#include "ui_synchrotimerclient.h"
#include <QDebug>
#include <wtypes.h>
#include <QRegularExpressionValidator>
#include <QValidator>
#include <QTimer>
#include <QMessageBox>
#define cout qDebug() << "[" << __FILE__ << ":" << __LINE__ << "]"

SynchroTimerClient::SynchroTimerClient(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::SynchroTimerClient)
{
    ui->setupUi(this);

    m_UdpSocket = new QUdpSocket;
    m_autoSetDate = new QTimer();

    initData();

    connect(m_UdpSocket,&QUdpSocket::readyRead,this,&SynchroTimerClient::processPendingDatagram);
    connect(m_autoSetDate,&QTimer::timeout,this,&SynchroTimerClient::autoSynDate);
}

void SynchroTimerClient::initData()
{
    if(!ui->textBrowser->toPlainText().isEmpty()){
        ui->textBrowser->clear();
    }
    ui->AutoSetDateCBox->setEnabled(false);

    ui->PortLEdit->setText("10012");
    m_UdpSocket->bind(10013);

    ui->ClientDTEdit->setEnabled(false);
    ui->ClientDTEdit->setDisplayFormat("yyyy年M月d日 HH:mm:ss");
    ui->ClientDTEdit->setDateTime(QDateTime::currentDateTime());
    ui->ClientDTEdit->setTimeZone(QTimeZone::systemTimeZone());


    QRegularExpression regExp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5] | 2[0 - 4][0 - 9] | [01] ? [0 - 9][0 - 9] ? )\\b");
    QValidator *validator = new QRegularExpressionValidator(regExp, this );
    ui->IPAddressLEdit->setValidator(validator);
    ui->IPAddressLEdit->setInputMask("000.000.000.000");
    ui->IPAddressLEdit->setText("127.0.0.1");
}

SynchroTimerClient::~SynchroTimerClient()
{
    delete m_autoSetDate;
    delete m_UdpSocket;
    delete ui;
}

void SynchroTimerClient::on_LinkBtn_clicked()
{
    if(!m_UdpSocket)
    {
        return;
    }

    if(ui->LinkBtn->text() == "连接")
    {
        sendMessage("connect");
        ui->AutoSetDateCBox->setEnabled(true);
        ui->LinkBtn->setText("已连接");
    }
    else
    {
        sendMessage("disconnect");
        m_UdpSocket->close();
        initData();

        ui->LinkBtn->setText("连接");
    }
}

void SynchroTimerClient::processPendingDatagram()
{
    ui->textBrowser->setText("连接服务器成功");
    QByteArray c_Receiver;
    //初始化QByteArray空间
    c_Receiver.resize(m_UdpSocket->pendingDatagramSize());
    qint64 len = m_UdpSocket->readDatagram(c_Receiver.data(),c_Receiver.size());
    if(len > 0)
    {
        m_DateTime = QDateTime::fromString(c_Receiver).toLocalTime();
        ui->ClientDTEdit->setDateTime(m_DateTime);
    }
}

void SynchroTimerClient::on_SetLocalTimeBtn_clicked()
{
    //qDebug() << "当前时间:"<< m_DateTime;
    SYSTEMTIME st;
    GetLocalTime(&st);//初始化st结构体
    st.wYear = m_DateTime.date().year();
    st.wMonth = m_DateTime.date().month();
    st.wDay = m_DateTime.date().day();
    st.wHour = m_DateTime.time().hour();
    st.wMinute = m_DateTime.time().minute();
    st.wSecond = m_DateTime.time().second();
    st.wMilliseconds = m_DateTime.time().msec();
    SetLocalTime(&st);
    if (!SetLocalTime(&st)) {
        // 处理错误
        QMessageBox::warning(this,"waring","请使用管理员权限运行");
        // 根据 dwError 进行相应的错误处理
    }
}


void SynchroTimerClient::on_AutoSetDateCBox_stateChanged(int arg1)
{
    if(arg1){
        m_autoSetDate->start(1000);
    }
    else{
        m_autoSetDate->stop();
    }
}

void SynchroTimerClient::autoSynDate(){
    on_SetLocalTimeBtn_clicked();
}

void SynchroTimerClient::sendMessage(QByteArray message){
    m_UdpSocket->writeDatagram(message.data(),message.size(),QHostAddress(ui->IPAddressLEdit->text()),ui->PortLEdit->text().toInt());
}

